package cn.xxstudy.visitshop.widget

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import cn.xxstudy.visitshop.R
import cn.xxstudy.visitshop.base.adapter.OnItemClickListener
import cn.xxstudy.visitshop.util.load
import cn.xxstudy.visitshop.ui.activity.main.fragment.home.model.BannerData
import kotlinx.android.synthetic.main.ui_banner.view.*

/**
 * @author ：DELL on 2021/3/24 .
 * @packages ：cn.xxstudy.visitshop.widget .
 * TODO:Banner
 */
class Banner : FrameLayout, LifecycleObserver {
    private var listener: OnItemClickListener<BannerData>? = null
    private var mAdapter: BannerAdapter
    private val loopCycle = 3000L
    private val handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            if (msg.what == 0) {
                viewPager.currentItem += 1
                sendEmptyMessageDelayed(0, loopCycle)
            }
        }
    }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    @SuppressLint("ClickableViewAccessibility")
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        mAdapter = BannerAdapter()
        View.inflate(context, R.layout.ui_banner, this)
        viewPager.adapter = mAdapter
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                indicator.selectedIndex = position % mAdapter.list.size
            }
        })

        viewPager.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> handler.removeMessages(0)
                MotionEvent.ACTION_UP -> handler.sendEmptyMessageDelayed(0, loopCycle)
            }
            return@setOnTouchListener super.onTouchEvent(event)
        }
    }

    fun setAdapterData(list: ArrayList<BannerData>) {
        mAdapter.list = list
        indicator.setConfig(list.size, Indicator.ROUND)
    }

    fun setOnItemClickListener(listener: OnItemClickListener<BannerData>) {
        this.listener = listener
    }


    inner class BannerAdapter : RecyclerView.Adapter<BannerViewHolder>() {
        //图片地址、详情地址
        var list = ArrayList<BannerData>()
            set(value) {
                field = value
                notifyDataSetChanged()
            }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BannerViewHolder {
            val rootView =
                LayoutInflater.from(parent.context).inflate(R.layout.item_banner, parent, false)
            return BannerViewHolder(rootView)
        }

        override fun getItemCount() = if (list.size == 0) 0 else Int.MAX_VALUE

        override
        fun onBindViewHolder(holder: BannerViewHolder, position: Int) {
            holder.bannerViewImg.load(
                context,
                "http://192.168.1.14:8000${list[position % list.size].imgUrl}"
            )
            holder.itemView.setOnClickListener {
                listener?.onClickItem(position, list[position % list.size])
            }
        }
    }

    inner class BannerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val bannerViewImg = itemView.findViewById<ImageView>(R.id.bannerItemImg)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun pauseLoopBanner() {
        handler.removeMessages(0)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun startLoopBanner() {
        handler.removeMessages(0)
        handler.sendEmptyMessageDelayed(0, loopCycle)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun stopLoopBanner() {
        handler.removeCallbacksAndMessages(null)
    }

}